package com.bardsoftware.foronuvolo.server;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import com.bardsoftware.foronuvolo.client.AddCommentService;
import com.bardsoftware.foronuvolo.data.Discussion;
import com.bardsoftware.foronuvolo.data.DiscussionsViewItem;
import com.bardsoftware.foronuvolo.data.DiscussionsViewItem.FormattedText;
import com.bardsoftware.foronuvolo.data.ForumUser;
import com.bardsoftware.foronuvolo.data.Message;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskHandle;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
import com.google.gdata.util.common.base.CharEscapers;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class AddCommentServiceImpl extends RemoteServiceServlet
implements AddCommentService {
    private static WikiMessageFormatter formatter = new WikiMessageFormatter();

    public String addComment(String discussionRefID, String unsafeMessage) {
        if (!getThreadLocalRequest().getRequestURL().toString().startsWith(ForoNuvoloConstants.FORUM_DOMAIN)) {
            return null;
        }
        ForumUser user = com.bardsoftware.foronuvolo.server.UserService.getUser(getThreadLocalRequest());
        if (!user.canWrite()) {
            return null;
        }
        Discussion d = Discussion.findByRefID(discussionRefID);
        if (d == null) {
            return null;
        }
        Message m = new Message(null, user, unsafeMessage, new Date());
        d.addMessage(m);
        DiscussionsViewPage.resetDiscussionViewPageCache();
        TaskOptions options = TaskOptions.Builder.url(ForoNuvoloConstants.INDEX_PATH)
            .param("start", d.getCreationOrder())
            .param("nonext", "true")
            .method(TaskOptions.Method.GET);
        TaskHandle add = QueueFactory.getDefaultQueue().add(options);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(JspHelper.getJspName("format_comment.jsp"));
        getThreadLocalRequest().setAttribute("nickname", m.getUserDisplayName());
        getThreadLocalRequest().setAttribute(
                "message", formatter.format(CharEscapers.htmlEscaper().escape(m.getText())).text);
        getThreadLocalRequest().setAttribute("date", m.getCreation());
        try {
            return JspHelper.forward(getThreadLocalRequest(), getThreadLocalResponse(), dispatcher);
        } catch (ServletException e) {
            e.printStackTrace();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    public String formatPreview(String message) {
        WikiMessageFormatter formatter = new WikiMessageFormatter();
        FormattedText formatted = DiscussionsViewItem.format(message, formatter, "{0}");
        return formatted.text;
    }
}
